
<template>

  <div class="signature-pad" :style="{paddingTop:(windowInnerHeight - Math.ceil((windowInnerWidth - 10)/2.15))/10 +'px'}" :key="signedVersionKey">
      <!-- 搞标题 -->
      {{ evetn }}
      <div @touchmove.prevent="preventScroll">
        <canvas ref="canvas" @touchstart="startDrawing" @touchmove="draw" @touchend="stopDrawing" @touchcancel="stopDrawing"></canvas>
        <div style="display: flex;justify-content: space-around;">
            <a-button class="blue-btn" type="primary" @click="saveSignature()">提交</a-button>
            <a-button class="blue-btn" type="primary" @click="clearCanvas()">重签</a-button>
            <a-button class="blue-btn" type="primary" @click="closeClick()">关闭</a-button>
        </div>
      </div>
  </div>
</template>

  <script>
  import { jcylxdjcjuploadMyQm } from './service/index'
  export default {
    data() {
      return {
        drawing: false,
        context: null,
        lastX: 0,
        lastY: 0,
        isPortrait: true,
        screenOrientation:screen.orientation,
        windowOrientation:window.orientation,
        windowInnerHeight:window.innerHeight,
        windowInnerWidth:window.innerWidth,
        imgSrc:'',
        currentId:'',
        currentIdKey:null,
        formField:{
          frylx: '企业'
        },
        validateArr:[],
        validateIdData:[
          'fbm','fzw','frylx'
        ],
        frylx: '',
        stepNum: 1,
        signedVersionKey: null,
        isDraw: false,
        Id: '',
        evetn:"",
      };
    },
    mounted() {
      document.title = 'xx“技术审评”审评查验信息一体化智慧管理系统'
      this.context = this.$refs.canvas.getContext('2d');
      this.$nextTick(()=>{
        this.resizeCanvas();
      })
      var str = decodeURIComponent(window.location.href);
      //截取类型
      const startIndex = str.indexOf("?type=") + 6;
      const endIndex = str.indexOf("?id=");
      this.frylx = str.substring(startIndex, endIndex)

      this.Id = this.$route.query.id
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.checkScreenOrientation);
    },
    methods: {
        preventScroll(event){
          if (!this.$refs.canvas.contains(event.target)) {
            // 如果不是画布上的事件，则阻止滚动
            event.preventDefault();
          }
        },
        resizeCanvas() {
            const canvas = this.$refs.canvas;
            // 设置canvas宽度为屏幕宽度的一定比例，例如80%
            // canvas.width = window.innerWidth * 0.8;
            canvas.width = Math.ceil(window.innerWidth - 10);
            // 设置canvas高度为屏幕高度的一定比例，例如80%
            // canvas.height = window.innerHeight * 0.5;
            canvas.height = Math.ceil((window.innerWidth - 10)/2);
        },
        startDrawing(event) {
            this.drawing = true;
            const rect = this.$refs.canvas.getBoundingClientRect();
            // 获取触摸点的页面坐标
            const touch = event.touches[0];
            // 转换为canvas的局部坐标
            this.lastX = touch.clientX - rect.left;
            this.lastY = touch.clientY - rect.top;
        },
        draw(event) {
            if (!this.drawing) return;
            const rect = this.$refs.canvas.getBoundingClientRect();
            // 获取触摸点的页面坐标
            const touch = event.touches[0];
            // 转换为canvas的局部坐标
            const x = touch.clientX - rect.left;
            const y = touch.clientY - rect.top;
            this.context.lineWidth = 4; // 设置画线的粗细（这里示意设置为5）
            this.context.strokeStyle = 'black'; // 设置画线的颜色
            // 在canvas上绘制线条
            this.context.beginPath();
            this.context.moveTo(this.lastX, this.lastY);
            this.context.lineTo(x, y);
            this.context.stroke();
            // 更新上一个点的坐标
            [this.lastX, this.lastY] = [x, y];
            this.isDraw = true
        },
        stopDrawing() {
            this.drawing = false;
        },
        clearCanvas() {
            // //console.log('获取路由',this.$route.query.id)
            this.context.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height);
            this.drawing = false;
            this.lastX = 0;
            this.lastY = 0;
            this.isDraw = false
        },
        closeClick(){
          if (typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {
            // 调用微信JS-SDK的closeWindow方法关闭当前页面
            WeixinJSBridge.invoke('closeWindow');
          } else {
            // 如果微信JS-SDK未加载，则使用普通方式尝试关闭窗口
            window.close();
          }
        },
        validateChange(val){
            // validateArr
            //validateIdData
            this.validateArr = []
            this.validateIdData.forEach(item=>{
                if(!val[item]){
                    if(!this.validateArr.filter(l=>l == item).length){
                        this.validateArr.push(item)
                    }
                }
            })
            //console.log(this.validateArr)
        },
        saveSignature() {
          let that = this
          this.$confirm({
            title:'您确认要提交签名吗？',
            onOk() {
              const canvas = that.$refs.canvas;
              // 获取canvas元素
              const dataUrl = canvas.toDataURL()

              // 创建新的image元素
              const image = new Image();
              image.src = dataUrl
              // 在加载完成时触发事件处理函数
              image.onload = function() {
                //console.log('我进不到这里')
                // 创建新的canvas元素
                const resizedCanvas = document.createElement('canvas');

                // 设置resizedCanvas的宽度和高度
                resizedCanvas.width = 172; // 自定义目标尺寸
                resizedCanvas.height = 80;
                // //console.log(image)

                // 在resizedCanvas上绘制原始图像
                resizedCanvas.getContext('2d').drawImage(image, 0, 0, resizedCanvas.width, resizedCanvas.height);

                // 将resizedCanvas转换为Blob对象
                const base64String  = resizedCanvas.toDataURL("image/png");
                const base64Data = base64String.split(',')[1];

                // 将Base64字符串转换为ArrayBuffer
                const byteCharacters = atob(base64Data);
                const byteArrays = [];

                for (let offset = 0; offset < byteCharacters.length; offset += 512) {
                  const slice = byteCharacters.slice(offset, offset + 512);

                  const byteNumbers = new Array(slice.length);
                  for (let i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                  }

                  const byteArray = new Uint8Array(byteNumbers);
                  byteArrays.push(byteArray);
                }

                const blob = new Blob(byteArrays, { type: 'image/png' });

                // 现在你有一个Blob对象，你可以将其视为File对象
                const file = new File([blob], 'image.png', { type: 'image/png' });

                //截取id
                // var jqStr = "?id="
                // var str = decodeURIComponent(window.location.href);
                // //截取jqStr之前字符串
                // var str1 = str.substring(0, str.indexOf(jqStr));
                // //截取jqStr之后字符串
                // var str2 = str.substring(str1.length+jqStr.length, str.length);
                // //console.log('id:',str2)

                //截取类型
                // const startIndex = str.indexOf("?type=") + 6;
                // const endIndex = str.indexOf("?id=");
                // var frylx = str.substring(startIndex, endIndex)
                // //console.log('扫码类型：',frylx)

                // 在这里你可以对file对象进行操作，例如上传到服务器
                //console.log(file);
                const fileData = new FormData();
                fileData.append("file",file);
                fileData.append("id",that.Id);
                fileData.append("fbm",that.formField.fbm);
                fileData.append("fzw",that.formField.fzw);
                fileData.append("frylx",that.formField.frylx);

                jcylxdjcjuploadMyQm(fileData).then(res=>{
                  if(res.code ==  200){
                    that.stepNum = 2
                    that.signedVersionKey = Date.now()
                  }else{
                    that.$message.warning(res.message)
                  }
                })
              };
            }
          })

        },
        preventScroll(event){
          //console.log(event)
          this.evetn = event
          if (!this.$refs.canvas.contains(event.target)) {
            // 如果不是画布上的事件，则阻止滚动
            event.preventDefault();
          }
        },
    }
  };
  </script>

  <style lang="less" scoped>
  .signature-pad {
    margin: 0;
    padding: 0;
    /* transform: rotate(90deg); */
    width: 100%;
    height: 100vh;
    overflow: hidden;
    text-align: center;

    position: relative;
  }
  canvas {
    border: 1px solid #000;
    /* width: 100%;
    height: auto; */
  }
  .meetingAttendanceFilling-table-content {
    .inspector-table-from-d{
        margin:10px;
        display: flex;
        align-items: center;
        .inspector-asterisk-v{
            color:#f5222d;
            font-size: 24px;
            display: flex;
            width: 6px;
            height: 16px;
            line-height: 21px;
        }
        .inspector-table-text{
            display: flex;
            align-items: center;
            .table-text-s{
                font-weight: 600;
                text-align: right;
                display: flex;
                justify-content: flex-end;
                width: 85px;
                font-size:18px;
                .inspector-asterisk-v{
                    padding-right: 10px;
                    line-height:27px;
                }
                .first-asterisk-v{
                    line-height: 50px;
                }
            }
        }

        .left-text-v{

        }
        .right-content-f{
            flex: 1;
            font-size:18px;
            input {
              background: #fff;
              font-size: 26px;
            }
            .ant-input:focus {
              box-shadow: none;
            }
            .inspector-table-code-btn-box{
                height: 32px !important;
                width: 110px;
            }
            .typeCheck-div {

                // margin-bottom: 10px;
                line-height: 1.8;
            }
            .ant-form {
              .ant-row {
                margin-bottom: 0 !important;
                margin-top: 20px;
                // /deep/ input:-webkit-autofill {
                //   -webkit-box-shadow: 0 0 0 0px transparent inset !important;
                //   background-color: transparent !important;
                // }
                // input:-internal-autofill-previewed,
                // input:-internal-autofill-selected {
                //   // -webkit-text-fill-color: #FFFFFF !important;
                //   outline: none;
                //   transition: background-color 5000s ease-in-out 0s !important;
                //   background-color: transparent !important;
                // }
                // /deep/ input:-internal-autofill-selected {
                //     transition: background-color 5000s ease-in-out 0s !important;
                //     background-color: transparent !important;
                // }
              }
            }
        }
        .right-content-v{
            flex: 1;
            font-size:18px;
            .inspector-table-code-btn-box{
                height: 32px;
                width: 88px;
            }
            .typeCheck-div {

                // margin-bottom: 10px;
                line-height: 1.8;
            }
        }
        .email-suffix-v{
            display: flex;
            align-items: center;
        }


    }
    .tips-flex{
            display: flex;
            padding-left: 96px;
            padding-bottom: 5px;
            .tips-text-v{
                color: #f5222d;
            }
        }
  }
  </style>

